package com.yxh.activity;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Vector;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.yxh.R;
import com.yxh.ZybApplication;
import com.yxh.dto.LessonDto;
import com.yxh.dto.UserDto;
import com.yxh.service.DataService;
import com.yxh.service.Task;
import com.yxh.zxing.camera.CameraManager;
import com.yxh.zxing.decoding.CaptureActivityHandler;
import com.yxh.zxing.decoding.InactivityTimer;
import com.yxh.zxing.view.ViewfinderView;

/**
 * 二维码扫描
 * 
 * @author luoming
 */
public class ClassAddByQrCodeActivity extends BaseActivity implements Callback,
		OnClickListener {
	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_class_add_by_qrcode);

		/*** top view ***/
		((TextView) findViewById(R.id.head_layout_tv)).setText("二维码扫描");

		overridePendingTransition(R.anim.enter_righttoleft, R.anim.noanim);
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		super.onResume();

		CameraManager.init(ZybApplication.getContext());

		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);

		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;
	}

	/**
	 * 处理扫描结果
	 * 
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		String code = result.getText();
		if (TextUtils.isEmpty(code)) {
			return;
		}

		/** 震动 **/
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();

		goAddClass(code);
	}

	private void goAddClass(String code) {
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "main/get_2dcode");
		map.put("code", code);
		getData(map, Task.ADD_LESSON_FOR_CODE, 1);
	}

	private void commitCode(String code) {
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "lesson/get_lesson_packs");
		map.put("lesson_packs_id", code);
		getData(map, Task.GET_LESSON_PACKS_CODE, 1);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void refresh(Object... param) {
		try {
			int operType = (Integer) param[0];
			Object obj = param[1];
			switch (operType) {

			case Task.ADD_LESSON_FOR_CODE:
				if (obj != null) {
					UserDto dto = (UserDto) obj;
					if (DataService.DATA_SUCCESS.equals(dto.result)) {
						if ("1".equals(dto.userType)) {// 医生

						} else if ("2".equals(dto.userType)) { // 用户

						} else if ("3".equals(dto.userType)) { // 课程
							commitCode(dto.uid);
						}
					} else {
						closeDialog();
						showToast(dto.message);
					}
				} else {
					closeDialog();
					showToast("网络连接异常,请检查网络");
				}
				break;

			case Task.GET_LESSON_PACKS_CODE:
				closeDialog();
				if (obj != null) {
					List<LessonDto> list = (ArrayList<LessonDto>) obj;
					if (DataService.DATA_SUCCESS.equals(list.get(0).result)) {
						Intent it = new Intent(mContext,
								ClassSelectActivity.class);
						it.putExtra("list", (Serializable) list);
						startActivity(it);
						finish();
					} else
						showToast(list.get(0).message);

				} else {
					showToast("网络连接异常,请检查网络");
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View view) {
		
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

}